package com.example.JPetStore.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.JPetStore.Common;
import com.example.JPetStore.common.AlipayConfig;
import com.example.JPetStore.dao.CartDao;
import com.example.JPetStore.dao.OrderDao;
import com.example.JPetStore.domain.Order;
import com.example.JPetStore.domain.User;
import com.example.JPetStore.dto.CartDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;

@Controller
@RequestMapping("/PayController")
public class PayController {
    @Autowired
    OrderDao orderDao;
    @Autowired
    CartDao cartDao;
    @RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8")
//    @ResponseBody
    public ModelAndView goAlipay(HttpSession session, HttpServletResponse response, @RequestParam("cart_id")String cartId, @RequestParam("address")String address,
                           @RequestParam("order_phone")String orderPhone, @RequestParam("delivery_name")String deliveryName,
                           @RequestParam("item_number")String itemNumber, @RequestParam("payment_method")String paymentMethod) throws Exception {

        ModelAndView mv=new ModelAndView();

        User user= Common.checkLogin(mv,session);
        if(user==null) {
            return mv;
        }

        if(cartId==null||orderPhone==null||deliveryName==null||address==null||itemNumber==null||paymentMethod==null){
            Common.sendErrorMessage(mv, "缺少参数！", "/catalog/MainController");
            return mv;
        }

        CartDto cart=cartDao.queryCartById(cartId,user.getUserId());

        if(cart==null){
            Common.sendErrorMessage(mv, "购物车数据不存在！", "/catalog/MainController");
            return mv;
        }



        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);


        Order order = new Order();
        order.setAddress(address);
        order.setOrderPhone(orderPhone);
        order.setDeliveryName(deliveryName);
        order.setUserId((cart.getUserId()+""));
        order.setItemId(cart.getItemId());
        order.setItemIntroduction(cart.getItemIntroduction());
        order.setItemPrice(cart.getItemPrice());
        order.setItemNumber(itemNumber);
        order.setPaymentMethod(paymentMethod);
        order.setTotalPrice((new BigDecimal(cart.itemPrice)).multiply(new BigDecimal(itemNumber)).toString());

        orderDao.addOrder(order);

//        cartDao.removeCart(cartId, user.getUserId());

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = Integer.toString(order.getOrderId());
        //付款金额，必填
        String total_amount = order.getTotalPrice();
        //订单名称，必填
        String subject = order.getItemId();
        //商品描述，可空
        String body = order.getItemIntroduction();

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1c";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        mv.addObject("form",result);
        mv.setViewName("/pay/goAlipay");
        return mv;
    }
}